<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="login-header">
          <h2>会议室预订系统</h2>
        </div>
      </template>
      
      <el-form :model="form" :rules="rules" ref="loginForm">
        <el-form-item prop="usertype">
          <el-radio-group v-model="form.usertype">
            <el-radio-button label="admin">管理员</el-radio-button>
            <el-radio-button label="employee">员工</el-radio-button>
            <el-radio-button label="customer">客户</el-radio-button>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="请输入账号" prefix-icon="User" />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" show-password prefix-icon="Lock" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
          <el-button @click="$router.push('/register')">注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { login } from '@/api/auth'
import { ElMessage } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()

const form = ref({
  username: '',
  password: '',
  usertype: 'customer'
})

const rules = {
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  usertype: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
}

const loginForm = ref(null)
const loading = ref(false)

const handleLogin = () => {
  loginForm.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      const response = await login({
        username: form.value.username,
        password: form.value.password,
        usertype: form.value.usertype
      })
      console.log(response)
      authStore.login({
        token: response.token,
        user_id: response.user_id,
        name: response.name,
        user_type: response.user_type,
        status: response.status
      })
      ElMessage.success('登录成功')
    } catch (error) {
      console.error(error)
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
}

.login-header {
  text-align: center;
}

.el-form-item:last-child {
  margin-bottom: 0;
}
</style>